package com.heatingcharge.controller.pay.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.heatingcharge.common.util.ChargeModeEnum;
import com.heatingcharge.common.util.R;
import com.heatingcharge.entity.pay.AliPayBean;
import com.heatingcharge.param.ChargeInfoParam;
import com.heatingcharge.service.pay.IAliPayService;
import com.heatingcharge.service.pay.IPayInfoService;
import com.ijpay.alipay.AliPayApi;
import com.ijpay.alipay.AliPayApiConfig;
import com.ijpay.alipay.AliPayApiConfigKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description: heating_charge_server
 * User: Devin
 * Date: 2019-12-13
 * Time: 14:50
 */
@RestController
@RequestMapping("/aliPay")
@Slf4j
public class AliPayController extends AbstractAliPayApiController  {
    @Autowired
    AliPayBean aliPayBean;
    @Autowired
    IAliPayService aliPayService;
    @Autowired
    IPayInfoService payInfoService;


    @GetMapping(value="",produces = "application/json; charset=utf-8")
    public String index() {
        return "欢迎使用支付宝支付";
    }

    @GetMapping("/pcPay")
    public void pay(ChargeInfoParam chargeInfoParam,
                    HttpServletResponse response) {
        try {
            aliPayService.pcPay(chargeInfoParam,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @GetMapping("/test")
    public R payTest(HttpServletResponse response)  {
        try {
            String f = aliPayService.payTest(response);
            log.info(f);
            return R.ok(f);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

    /**
     * 通知URL
     * @param request
     * @return
     */
    @PostMapping(value = "/notify_url")
    public String notifyUrl(HttpServletRequest request) {
        try {
            // 获取支付宝POST过来反馈信息
            Map<String, String> params = AliPayApi.toMap(request);
            boolean verifyResult = AlipaySignature.rsaCheckV1(params, aliPayBean.getPublicKey(), "UTF-8", "RSA2");
            if (verifyResult) {
                // 处理支付宝支付结果
                payInfoService.disposePayResult(params, ChargeModeEnum.ALIPAY.getCode());
                log.info("notify_url 验证成功succcess");
                return "success";
            } else {
                log.info("notify_url 验证失败");
                return "failure";
            }
        } catch (AlipayApiException e) {
            log.info("notify_url 验证失败");
            e.printStackTrace();
            return "failure";
        }
    }

    /**
     * 返回URL
     * @param request
     * @return
     */
    @GetMapping(value = "/return_url",produces = "application/json; charset=utf-8")
    public String returnUrl(HttpServletRequest request) {
        try {
            // 获取支付宝GET过来反馈信息
            Map<String, String> map = AliPayApi.toMap(request);
//            for (Map.Entry<String, String> entry : map.entrySet()) {
//                System.out.println(entry.getKey() + " = " + entry.getValue());
//            }

            boolean verifyResult = AlipaySignature.rsaCheckV1(map, aliPayBean.getPublicKey(), "UTF-8",
                    "RSA2");

            if (verifyResult) {
                // TODO 请在这里加上商户的业务逻辑程序代码
                log.info("return_url 验证成功");

                return "支付成功";
            } else {
                log.info("return_url 验证失败");
                // TODO
                return "return_url 验证失败";
            }
        } catch (AlipayApiException e) {
            log.info("return_url 验证失败");
            e.printStackTrace();
            return "return_url 验证失败";
        }
    }

    @Override
    public AliPayApiConfig getApiConfig() throws AlipayApiException {
        AliPayApiConfig aliPayApiConfig;
        try {
            aliPayApiConfig= AliPayApiConfigKit.getApiConfig(aliPayBean.getAppId());
        } catch (Exception e) {
            aliPayApiConfig = AliPayApiConfig.builder()
                    .setAppId(aliPayBean.getAppId())
                    .setAliPayPublicKey(aliPayBean.getPublicKey())
                    .setAppCertPath(aliPayBean.getAppCertPath())
                    .setAliPayCertPath(aliPayBean.getAliPayCertPath())
                    .setAliPayRootCertPath(aliPayBean.getAliPayRootCertPath())
                    .setCharset("UTF-8")
                    .setPrivateKey(aliPayBean.getPrivateKey())
                    .setServiceUrl(aliPayBean.getServerUrl())
                    .setSignType("RSA2")
                    // 普通公钥方式
                    .build();
            // 证书模式
            //.buildByCert();
        }

        return aliPayApiConfig;
    }
}
